<!-- 新增/编辑指标 -->
<template>
  <a-drawer
    width="45%"
    :visible="props.visible"
    @ok="handleOk"
    @cancel="handleCancel"
    draggable
    title-align="center"
    unmountOnClose
  >
    <template #title> {{ props.data?.id ? '编辑指标' : '新增指标' }} </template>
    <div>
      <a-form
        :model="formData.data"
        ref="refForm"
        :rules="rules"
        :label-col-props="{ span: 6, offset: 0 }"
        :wrapper-col-props="{ span: 18, offset: 0 }"
      >
        <a-form-item label="目标(O)" field="name" show-colon>
          <a-input v-model="formData.data.name" />
        </a-form-item>
        <a-form-item
          label="(O)权重/分值"
          field="weight"
          show-colon
          :tooltip="`最大权重不能超过100`"
        >
          <a-input-number
            v-model="formData.data.weight"
            :max="100"
            :precision="2"
            :min="0.01"
            hide-button
          >
          </a-input-number>
          <a-select
            v-model="formData.data.weightType"
            :style="{ width: '80px' }"
            placeholder="权重类型"
          >
            <a-option
              v-for="item of weightTypeOptions"
              :key="item.value"
              :value="item.value"
              >{{ item.lable }}</a-option
            >
          </a-select>
        </a-form-item>
        <a-form-item
          label="关键成果(KR)"
          field="performanceKeyResultsIndexLibraryUse"
          show-colon
        >
          <a-table
            :data="formData.data.performanceKeyResultsIndexLibraryUse"
            stripe
          >
            <template #columns>
              <a-table-column title="关键成果(KR)" data-index="">
                <template #cell="{ record, rowIndex }">
                  <a-form-item
                    :field="`performanceKeyResultsIndexLibraryUse.${rowIndex}.result`"
                    :rules="[
                      {
                        required: true,
                        message: '请输入'
                      }
                    ]"
                  >
                    <a-textarea
                      v-model="record.result"
                      show-word-limit
                      :max-length="50"
                      :auto-size="{
                        minRows: 2
                      }"
                    ></a-textarea>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column title="KR权重(%)" data-index="">
                <template #cell="{ record, rowIndex }">
                  <a-form-item
                    :field="`performanceKeyResultsIndexLibraryUse.${rowIndex}.weight`"
                    :rules="[
                      {
                        required: true,
                        message: '请输入'
                      },
                      {
                        validator: validateKrsWeight
                      }
                    ]"
                  >
                    <a-input-number
                      v-model="record.weight"
                      hide-button
                      :max="100 - krsMaxWeight + record.weight"
                      @change="
                        (value: number, _: Event, rowIndex: number) =>
                          changeKrsWeight(value, _, rowIndex)
                      "
                    ></a-input-number>
                  </a-form-item>
                </template>
              </a-table-column>
              <a-table-column title="操作" data-index="" :width="100">
                <template #cell="{ rowIndex }">
                  <IconFont
                    type="icon-add-def"
                    :size="26"
                    :style="{
                      marginRight: '10px',
                      cursor: 'pointer'
                    }"
                    @click="add(rowIndex)"
                  />
                  <a-tooltip
                    content="删除"
                    v-if="
                      formData.data.performanceKeyResultsIndexLibraryUse
                        .length > 1
                    "
                  >
                    <a-popconfirm
                      content="是否确认删除该条数据?"
                      @ok="del(rowIndex)"
                    >
                      <IconFont
                        type="icon-delete"
                        :size="26"
                        :style="{
                          cursor: 'pointer'
                        }"
                      />
                    </a-popconfirm>
                  </a-tooltip>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </a-form-item>
        <!-- <a-form-item label="备注" field="remark" show-colon>
          <a-textarea
            v-model="formData.data.remark"
            show-word-limit
            :max-length="50"
            :auto-size="{
              minRows: 4
            }"
          ></a-textarea>
        </a-form-item> -->
        <a-form-item label="状态" field="" show-colon>
          <a-switch
            v-model="formData.data.status"
            :checked-value="1"
            :unchecked-value="2"
            size="medium"
          >
            <template #checked> 启动 </template>
            <template #unchecked> 停止 </template>
          </a-switch>
          <!-- <a-radio-group v-model="formData.data.status">
            <a-radio :value="1">启动</a-radio>
            <a-radio :value="2">停止</a-radio>
          </a-radio-group> -->
        </a-form-item>
      </a-form>
      <!-- <CountSetting v-model:visible="countSettingVisiable"></CountSetting> -->
    </div>
    <template #footer>
      <a-space>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="handleOk">确认</a-button>
        <a-button v-if="!formData?.id" type="primary" @click="continueAdd"
          >确认并继续新增</a-button
        >
      </a-space>
    </template>
  </a-drawer>
</template>

<script lang="ts" setup>
import { cloneDeep } from 'lodash';
import { useAssessmentToolStore } from '@/store';
import { Message } from '@arco-design/web-vue';
import { OkrIndex } from '@/apis/management/performance/baseSetting/template/type';
import { GetOkrIndexRepeat } from '@/apis/management/performance/baseSetting/template';

const toolStore = useAssessmentToolStore();
const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框
    data?: OkrIndex; // 传进来的数据,
  }>(),
  {}
);

const emits = defineEmits(['update:visible', 'okrIndexEmit']);
let refForm = ref();
let countSettingVisiable = ref(false); // 是否设置计算公式弹出框
let isShowContinueBtn = ref(true); // 是否显示继续新增按钮
const formData = reactive<{ data: OkrIndex }>({
  data: {
    name: '', // 目标O
    weight: 0, // o权重/分值
    weightType: 1, //类型（1权重2分值
    status: 2, //状态（1启动 2停止
    // 关键成果krs
    performanceKeyResultsIndexLibraryUse: [
      {
        result: '',
        weight: 0
        // scorers
      }
    ]
    // result: [
    //   {
    //     name: '',
    //     weight: undefined
    //   }
    // ], // 关键成果krs
  }
});
const weightTypeOptions = Object.freeze([
  { value: 1, lable: '%' },
  { value: 2, lable: '分' }
]);
// 原始数据
const originData = {
  target: undefined, // 目标O
  weight: 0, // (O)权重/分值
  // 关键成果krs
  performanceKeyResultsIndexLibraryUse: [
    {
      result: '',
      weight: 0
      // scorers
    }
  ],
  // result: [
  //   {
  //     name: '',
  //     weight: undefined
  //   }
  // ], // 关键成果krs
  require: '', // 完成目标及时限要求
  standard: undefined, // 评分标准
  // weight: '', // 指标权重
  dataSource: undefined, // 评分人（userid）
  upper: '', // 评分上限
  remark: '', // 备注
  personne: 1, // 评分人是否开启 1开 2否
  // dimensionaId: '', // 维度id
  way: 1, // 考核评分 1直接输入
  hid: undefined // 目标id
};

// 校验kr权重
const validateKrsWeight = (val: number, cb: any) => {
  if (krsMaxWeight.value - val === 100)
    cb('权重总和已经达到100，若要继续新增请先调整其他的权重!');
};

// 校验(O)权重/分值
const validateweight = (val: number, cb: any) => {
  // console.log('====================================');
  // console.log(props.maxWeight);
  // console.log(props.data);
  // console.log('====================================');
  // if (
  //   props.maxWeight - (props?.data?.weight ? props?.data?.weight : 0) ===
  //   100
  // )
  //   cb('权重总和已经达到100，若要继续新增请先调整其他的权重!');
};
/**
 * 查重
 */
const validateName = async (value: any, cb: any) => {
  if (value === props.data?.name) return;
  const res = await GetOkrIndexRepeat({ name: formData.data.name });
  if (res?.code === 400) {
    cb('名称已存在!');
  }
};
const rules = reactive({
  name: [
    {
      required: true,
      message: '请输入'
    },
    {
      validator: validateName
    }
  ],
  weight: [
    {
      required: true,
      message: '请输入'
    },
    {
      validator: validateweight
    }
  ],
  performanceKeyResultsIndexLibraryUse: [
    {
      required: true,
      message: '请输入'
    }
  ]
  // weight: [
  //   {
  //     required: true,
  //     message: '请输入'
  //   }
  // ]
});

watch(
  () => props.visible,
  (newVal: boolean) => {
    // 如果是编辑，则赋值给formData
    if (newVal) {
      if (props.data) {
        formData.data = cloneDeep(props.data);

        isShowContinueBtn.value = false;
      } else {
        krsMaxWeight.value = 0;
        formData.data = cloneDeep(props.data);
      }
      // 如果设置了加权则要设置总分上限
      // formData.data.upper =
      //   toolStore.getCalculate === 2 && toolStore.upperLimit === 1
      //     ? toolStore.getUpperScore * props.weight * 0.01
      //     : undefined;
    } else {
      isShowContinueBtn.value = true;
      formData.data = cloneDeep(originData);
      krsMaxWeight.value = 0;
    }
  }
);

let krsMaxWeight = ref(0); // 储存kr权重，最高不能超过100

const changeKrsWeight = (val: number, _: Event, index: number) => {
  krsMaxWeight.value =
    formData.data.performanceKeyResultsIndexLibraryUse.reduce(
      (pre: any, cur: any) => pre + cur.weight,
      0
    );
};

// 新增一项
const add = (index: number) => {
  krsMaxWeight.value =
    formData.data.performanceKeyResultsIndexLibraryUse.reduce(
      (pre: any, cur: any) => pre + cur.weight,
      0
    );

  formData.data.performanceKeyResultsIndexLibraryUse.splice(index + 1, 0, {
    result: '',
    weight: 0
  });
};

const del = (index: number) => {
  krsMaxWeight.value -=
    formData.data.performanceKeyResultsIndexLibraryUse[index].weight;
  formData.data.performanceKeyResultsIndexLibraryUse.splice(index, 1);
};

const handleOk = async () => {
  if (await refForm.value.validate()) {
    return;
  }
  if (
    formData.data.performanceKeyResultsIndexLibraryUse.reduce(
      (pre: any, cur: any) => pre + cur.weight,
      0
    ) !== 100
  ) {
    Message.error('关键成果(KR)里的KR权重值总和必须为100！');
    return;
  }
  // const temp: any = [];
  // formData.data.result.forEach((item: any) => {
  //   temp.push({
  //     ...formData.data,
  //     resultName: item.name,
  //     resultWeight: item.weight
  //   });
  // });
  emits('okrIndexEmit', cloneDeep(formData.data));
  emits('update:visible', false);
};

const continueAdd = async () => {
  if (await refForm.value.validate()) {
    return;
  }
  if (
    formData.data.performanceKeyResultsIndexLibraryUse.reduce(
      (pre: any, cur: any) => pre + cur.weight,
      0
    ) !== 100
  ) {
    Message.error('关键成果(KR)里的KR权重值总和必须为100！');
    return;
  }
  emits('okrIndexEmit', cloneDeep(formData.data), true);
  emits('update:visible', true);
  formData.data = cloneDeep(originData);
  // 如果设置了加权则要设置总分上限
  // formData.data.upper =
  //   toolStore.getCalculate === 2 && toolStore.upperLimit === 1
  //     ? toolStore.getUpperScore * props.weight * 0.01
  //     : undefined;
};

const handleCancel = () => {
  emits('update:visible', false);
};
</script>

<style scoped lang="less">
.icon {
  cursor: pointer;
  font-size: 20px;
}
</style>
